package com.alibaba.citrus.cr.sales.plan.facade.service.salesplan.publish;

import com.alibaba.citrus.cr.common.annotation.FacadeInvoker;
import com.alibaba.citrus.cr.common.exception.FacadeException;
import com.alibaba.citrus.cr.common.util.DateUtils;
import com.alibaba.citrus.cr.sales.plan.dto.api.request.SalesPlanAdjustDetailSubTotalRequest;
import com.alibaba.citrus.cr.sales.plan.dto.api.response.SalesPlanSubTotalResponse;
import com.alibaba.citrus.cr.sales.plan.model.enums.SalesPlanStatusEnum;
import com.alibaba.citrus.cr.sales.plan.model.enums.SalesStatBizTypeEnum;
import com.alibaba.citrus.cr.sales.plan.model.enums.StatPoolTypeEnum;
import com.alibaba.citrus.cr.sales.plan.repository.PlatformEnhanceRepository;
import com.alibaba.citrus.cr.sales.plan.repository.SalesPlanAdjustDetailRepository;
import com.alibaba.citrus.cr.sales.plan.repository.SalesPlanLineRepository;
import com.alibaba.citrus.cr.sales.plan.repository.SalesPlanScItemExtendRepository;
import com.alibaba.citrus.cr.sales.plan.repository.request.OrganizationListQueryRequest;
import com.alibaba.citrus.cr.sales.plan.repository.request.PageQueryPlanScItemExtendRepoRequest;
import com.alibaba.citrus.cr.sales.plan.sdo.SalesPlanSDO;
import com.alibaba.citrus.cr.sales.plan.sdo.SalesPlanScItemExtendSDO;
import com.alibaba.citrus.cr.sales.plan.api.salesplan.publish.SalesPlanPublishQueryService;
import com.alibaba.citrus.cr.sales.plan.dto.api.request.DimensionDTO;
import com.alibaba.citrus.cr.sales.plan.dto.api.request.PageQueryPlanScItemExtendRequest;
import com.alibaba.citrus.cr.sales.plan.facade.service.SalesPlanCommonService;
import com.alibaba.citrus.cr.sales.plan.facade.service.SalesPlanOutCommonService;
import com.alibaba.cz.base.tool.log.Log;
import com.alibaba.cz.base.tool.page.PageResult;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.lattice2.epoch.sdk.model.Result;
import com.epoch.app.bcorder.model.dto.GetOrganizationSelectsRequest;
import com.epoch.app.bcorder.model.dto.GetOrganizationSelectsResponse;
import com.epoch.app.bcorder.model.dto.ScItemSDO;
import com.epoch.app.bcorder.model.dto.SearchCargoZoneListRequest;
import com.epoch.app.bcorder.model.dto.SearchCargoZoneListResponse;
import com.epoch.app.bcorder.model.dto.WarehouseInfo;
import com.epoch.app.bcorder.sales_plan.contract.dto.SubTotalCompanyCrmContractCountRequest;
import com.epoch.app.bcorder.sales_plan.contract.model.Contract;
import com.epoch.app.bcorder.sales_plan.contract.service.ContractService;
import com.epoch.app.bcorder.sales_plan.planscitemextend.dto.SubTotalCompanyReturnCountRequest;
import com.epoch.app.bcorder.sales_plan.planscitemextend.dto.SubTotalCompanyReturnCountResponse;
import com.epoch.app.bcorder.sales_plan.planscitemextend.service.PlanScItemExtendService;
import com.epoch.app.bcorder.sales_plan.salesplandetail.dto.SubTotalSalesPlanLineRequest;
import com.epoch.app.bcorder.service.BaseDataService;
import com.epoch.app.bcorder.service.UnifiedInventoryService;
import com.epoch.app.crplatformenhance.enums.OrganizationTypeEnum;
import com.epoch.app.crunifiedinventory.model.dto.GetCompanyInventoryRequest;
import com.epoch.app.crunifiedinventory.model.dto.WarehouseInventory;
import com.epoch.app.crunifiedinventory.service.CrUnifiedInventoryService;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections4.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @author yuhailin
 * @description:
 * @date 2021-09-27 10:37
 */
@Component
public class SalesPlanPublishQueryServiceImpl implements SalesPlanPublishQueryService {

    private static final Log log = Log.getLogger(SalesPlanPublishQueryServiceImpl.class);

    @Resource
    private SalesPlanScItemExtendRepository salesPlanScItemExtendRepository;

    @Resource
    private SalesPlanCommonService salesPlanCommonService;

    @Resource
    private SalesPlanOutCommonService salesPlanOutCommonService;

    @Resource
    private BaseDataService baseDataService;

    @Resource
    private UnifiedInventoryService unifiedInventoryService;

    @Resource
    private PlatformEnhanceRepository platformEnhanceRepository;

    @Resource
    private CrUnifiedInventoryService crUnifiedInventoryService;

    @Resource
    private ContractService contractService;

    @Resource
    private SalesPlanLineRepository salesPlanLineRepository;

    @Resource
    private SalesPlanAdjustDetailRepository salesPlanAdjustDetailRepository;

    @Resource
    private PlanScItemExtendService planScItemExtendService;

    @Override
    @FacadeInvoker
    public Result<PageResult<List<SalesPlanScItemExtendSDO>>> pageQueryPlanScItemExtendList(PageQueryPlanScItemExtendRequest pageQueryPlanScItemExtendRequest) {
        SalesPlanSDO salesPlan = salesPlanCommonService.checkSalesPlan(pageQueryPlanScItemExtendRequest.getPlanId());
        PageQueryPlanScItemExtendRepoRequest repoRequest = getQueryPlanScItemExtendRequest(pageQueryPlanScItemExtendRequest,salesPlan);
        PageResult<List<SalesPlanScItemExtendSDO>> listPageResult = salesPlanScItemExtendRepository.pageQueryPlanScItemExtendList(repoRequest);
        if (listPageResult != null && CollectionUtils.isNotEmpty(listPageResult.getContent())) {
            listPageResultConverter(listPageResult, salesPlan);
        }
        // 公司任务量要查询公司库存
        String orgBusinessUnitCode = salesPlan.getOrgBusinessUnitCode();
        try {
            refreshStock(listPageResult, pageQueryPlanScItemExtendRequest, orgBusinessUnitCode);
        } catch (Exception e) {
            log.error("月度计划发布查询货品库存异常", e);
        }
        return Result.success(listPageResult);
    }

    /**
     * 公司库存查询
     */
    private void refreshStock(PageResult<List<SalesPlanScItemExtendSDO>> listPageResult, PageQueryPlanScItemExtendRequest pageQueryPlanScItemExtendRequest, String orgBusinessUnitCode) {
        // 公司任务量要查询公司库存
        Integer queryBizType = pageQueryPlanScItemExtendRequest.getQueryBizType();
        List<String> scItemIdList = listPageResult.getContent().stream().map(SalesPlanScItemExtendSDO::getScItemId).collect(Collectors.toList());
        if (SalesStatBizTypeEnum.BUSINESS_UNIT.getOrganizationType().equals(queryBizType)) {
            if (StringUtils.isBlank(orgBusinessUnitCode)) {
                return;
            }
            // 查询公司下的每个货品的库存
            Map<String, String> stockForCompany = getStockForCompany(orgBusinessUnitCode, scItemIdList);
            List<SalesPlanScItemExtendSDO> content = listPageResult.getContent();
            if (MapUtils.isNotEmpty(stockForCompany)) {
                Map<String, String> finalStockMap = stockForCompany;
                content.forEach(salesPlanScItemExtendSDO -> {
                    String scItemId = salesPlanScItemExtendSDO.getScItemId();
                    String availableQuantity = finalStockMap.get(scItemId);
                    salesPlanScItemExtendSDO.setInventoryStr(availableQuantity);
                });
            }
            listPageResult.setContent(content);
        }
    }

    /**
     * 查询公司维度下的货品库存
     * 1、根据公司查销售组织
     * 2、根据销售组织查仓库
     * 3、根据仓库+货品id查仓库里的库存
     * 4、汇总为公司级别
     *
     * @param companyCode  分子公司编码
     * @param scItemIdList 货品idList
     * @return Map(货品id, 公司库存)
     */
    private Map<String, String> getStockForCompany(String companyCode, List<String> scItemIdList) {
        if (org.apache.commons.collections4.CollectionUtils.isEmpty(scItemIdList)) {
            return new HashMap<>();
        }
        // 1、获取分子公司下的销售组织
        GetOrganizationSelectsRequest getOrganizationSelectsRequest = new GetOrganizationSelectsRequest();
        getOrganizationSelectsRequest.setParentId(companyCode);

        log.info("查询业务单元下的销售组织请求参数：{}", JSON.toJSONString(getOrganizationSelectsRequest));
        GetOrganizationSelectsResponse organizationSelects = baseDataService.getOrganizationSelects(getOrganizationSelectsRequest);
        log.info("查询业务单元下的销售组织返回结果：{}", JSON.toJSONString(organizationSelects));
        if (null == organizationSelects) {
            throw new FacadeException("OTS-02-004-01-15-033");
        }
        List orgResult = organizationSelects.getResult();
        if (org.apache.commons.collections4.CollectionUtils.isEmpty(orgResult)) {
            throw new FacadeException("OTS-02-004-01-15-034");
        }
        List<Map> mapList = JSONObject.parseArray(JSON.toJSONString(orgResult), Map.class);
        List<String> orgIdList = mapList.stream().map(map -> map.get("value").toString()).collect(Collectors.toList());
        // 2、根据销售组织查仓库
        SearchCargoZoneListRequest searchCargoZoneListRequest = new SearchCargoZoneListRequest();
        searchCargoZoneListRequest.setModel(3);
        searchCargoZoneListRequest.setStatus(1);
        searchCargoZoneListRequest.setSize(1000);
        searchCargoZoneListRequest.setSaleOrgIdList(orgIdList);
        log.info("查询销售组织下的仓库请求参数：{}", JSON.toJSONString(searchCargoZoneListRequest));
        SearchCargoZoneListResponse searchCargoZoneListResponse = unifiedInventoryService.searchCargoZoneList(searchCargoZoneListRequest);
        log.info("查询销售组织下的仓库返回结果：{}", JSON.toJSONString(searchCargoZoneListResponse));
        if (null == searchCargoZoneListResponse || searchCargoZoneListResponse.getTotal() <= 0
                || org.apache.commons.collections4.CollectionUtils.isEmpty(searchCargoZoneListResponse.getResult())) {
            throw new FacadeException("OTS-02-004-01-15-035");
        }
        List<WarehouseInfo> warehouseInfoList = searchCargoZoneListResponse.getResult();
        List<String> warehouseIdList = warehouseInfoList.stream().map(WarehouseInfo::getId).collect(Collectors.toList());
        // 3、根据仓库+货品id查仓库里的库存
        GetCompanyInventoryRequest getCompanyInventoryRequest = new GetCompanyInventoryRequest();
        getCompanyInventoryRequest.setGoodsIds(scItemIdList);
        getCompanyInventoryRequest.setWarehouseAreaIdList(warehouseIdList);
        Result<List<WarehouseInventory>> listWarehouseStock = crUnifiedInventoryService.getCompanyInventory(getCompanyInventoryRequest);
        if (null == listWarehouseStock || !listWarehouseStock.isSuccess()) {
            throw new FacadeException("OTS-02-004-01-15-036");
        }
        List<WarehouseInventory> warehouseInventoryList = listWarehouseStock.getResult();
        if (org.apache.commons.collections4.CollectionUtils.isEmpty(warehouseInventoryList)) {
            throw new FacadeException("OTS-02-004-01-15-037");
        }
        // 根据货品id分组  每一个key代表一个货品下的所有仓库的库存量
        Map<String, List<WarehouseInventory>> listMap = warehouseInventoryList.stream().collect(Collectors.groupingBy(WarehouseInventory::getGoodsId));
        Map<String, String> result = new HashMap<>();
        for (String scItemId : listMap.keySet()) {
            List<WarehouseInventory> warehouseInventories = listMap.get(scItemId);
            if (org.apache.commons.collections4.CollectionUtils.isEmpty(warehouseInventories)) {
                continue;
            }
            WarehouseInventory warehouseInventory = warehouseInventories.get(0);
            String availableQuantityFormat = warehouseInventory.getAvailableQuantityFormat();
            // 一个货品在一个仓库只有一个库存
            result.put(scItemId, availableQuantityFormat);
        }
        return result;
    }

    private void listPageResultConverter(PageResult<List<SalesPlanScItemExtendSDO>> listPageResult, SalesPlanSDO salesPlan) {
        //获取货品外部编码
        Set<String> scItemSet = listPageResult.getContent().stream().map(SalesPlanScItemExtendSDO::getScItemId).collect(Collectors.toSet());
        Map<String, ScItemSDO> scItemMapByOutMap = salesPlanOutCommonService.getScItemMapByIds(scItemSet, false);
        listPageResult.getContent().forEach(x -> {
            if (scItemMapByOutMap != null) {
                ScItemSDO scItemSDO = scItemMapByOutMap.get(x.getScItemId());
                if (Objects.nonNull(scItemSDO)) {
                    x.setOuterId(scItemSDO.getOuterId());
                    x.setScItemName(scItemSDO.getTitle());
                }
            }
            if(x.getCompanyTaskCount() == null){
                x.setCompanyTaskCount(0);
            }
            if(x.getMonthFirstCompanyTaskCount() == null){
                x.setMonthFirstCompanyTaskCount(0);
            }
            if(x.getMonthMiddleCompanyTaskCount() == null){
                x.setMonthMiddleCompanyTaskCount(0);
            }
            if(x.getMonthLastCompanyTaskCount() == null){
                x.setMonthLastCompanyTaskCount(0);
            }
            x.setMonthReturnCount(x.getMonthFirstReturnCount() + x.getMonthMiddleReturnCount() + x.getMonthLastReturnCount());
            x.setMonthAdjustReturnCount(x.getMonthFirstAdjustReturnCount() + x.getMonthMiddleAdjustReturnCount() + x.getMonthLastAdjustReturnCount());

//            if (SalesPlanModelEnum.ADJUST_MODEL.getModel().equals(salesPlanScItemExtendSDO.getModel()) && salesPlanScItemExtendSDO.getCostInsuranceFreight() != 0
//            && salesPlan.getEstimateDiscount() != null){
//                salesPlanScItemExtendSDO.calculateAdjustPublicSatisfaction(salesPlanScItemExtendSDO.getCostInsuranceFreight(),salesPlan.getEstimateDiscount());
//            }
        });
    }

    @Override
    @FacadeInvoker
    public Result<SalesPlanSubTotalResponse> queryPublicStat(PageQueryPlanScItemExtendRequest pageQueryPlanScItemExtendRequest) {
        SalesPlanSDO salesPlan = salesPlanCommonService.checkSalesPlan(pageQueryPlanScItemExtendRequest.getPlanId());
        PageQueryPlanScItemExtendRepoRequest subTotalRequest = getQueryPlanScItemExtendRequest(pageQueryPlanScItemExtendRequest,salesPlan);
        SalesPlanSubTotalResponse salesPlanSubTotalResponse = salesPlanScItemExtendRepository.queryPlanScItemExtendSum(subTotalRequest);
        BigDecimal discount = (new BigDecimal(100).subtract(salesPlan.getEstimateDiscount())).divide(new BigDecimal(100),2,BigDecimal.ROUND_HALF_UP);

        SubTotalSalesPlanLineRequest queryDimension = getQueryDimension(subTotalRequest);
        //调整发布
        if(pageQueryPlanScItemExtendRequest.getModel()!=null && pageQueryPlanScItemExtendRequest.getModel().equals(2)){
            salesPlanSubTotalResponse.setReturnCount(salesPlanSubTotalResponse.getAdjustReturnCount());
            salesPlanSubTotalResponse.setBeforeReturnMoney(salesPlanSubTotalResponse.getAdjustBeforeReturnMoney());
            salesPlanSubTotalResponse.setReturnOutboundMoney(salesPlanSubTotalResponse.getAdjustReturnOutboundMoney());
            BigDecimal returnMoney = new BigDecimal(salesPlanSubTotalResponse.getBeforeReturnMoney()).multiply(discount);
            salesPlanSubTotalResponse.setReturnMoney(returnMoney.longValue());

            //查询调整明细合计得到总调整量
            SalesPlanAdjustDetailSubTotalRequest subTotalAdjustRequest = new SalesPlanAdjustDetailSubTotalRequest();
            BeanUtils.copyProperties(subTotalRequest, subTotalAdjustRequest);
            subTotalAdjustRequest.setAdjustId(subTotalRequest.getModelId());
            subTotalAdjustRequest.setBizId(CollectionUtils.isNotEmpty(subTotalRequest.getBizId())?subTotalRequest.getBizId().get(0):null);
            SalesPlanSubTotalResponse salesPlanSubTotalAdjustResponse = salesPlanAdjustDetailRepository.subTotalSalesPlanAdjustDetail(subTotalAdjustRequest);
            salesPlanSubTotalResponse.setAdjustCount(salesPlanSubTotalAdjustResponse.getAdjustCount());
            salesPlanSubTotalResponse.setAdjustOutboundMoney(salesPlanSubTotalAdjustResponse.getAdjustOutboundMoney());
            salesPlanSubTotalResponse.setBeforeAdjustMoney(salesPlanSubTotalAdjustResponse.getBeforeAdjustMoney());
            if(salesPlanSubTotalResponse.getBeforeAdjustMoney()!=null){
                BigDecimal adjustMoney = new BigDecimal(salesPlanSubTotalResponse.getBeforeAdjustMoney()).multiply(discount);
                salesPlanSubTotalResponse.setAdjustMoney(adjustMoney.longValue());
            }
            //合计月度计划明细, 获取计划量，任务量，初始任务量
            SubTotalSalesPlanLineRequest subTotalPlanRequest = new SubTotalSalesPlanLineRequest();
            if(Objects.nonNull(queryDimension)){
                BeanUtils.copyProperties(queryDimension, subTotalPlanRequest);
            }
            BeanUtils.copyProperties(subTotalRequest,subTotalPlanRequest);
            subTotalPlanRequest.setPlanId(Long.valueOf(subTotalRequest.getPlanId()));
            subTotalPlanRequest.setStatus(null);
            SalesPlanSubTotalResponse salesPlanSubTotalResponse2 = salesPlanLineRepository.subTotalSalesPlanLine(subTotalPlanRequest);
            salesPlanSubTotalResponse.setMonthCount(salesPlanSubTotalResponse2.getMonthCount());
            salesPlanSubTotalResponse.setBeforeMonthMoney(salesPlanSubTotalResponse2.getBeforeMonthMoney());
            salesPlanSubTotalResponse.setMonthMoney(salesPlanSubTotalResponse2.getMonthMoney());
            salesPlanSubTotalResponse.setTaskCount(salesPlanSubTotalResponse2.getTaskCount());
            salesPlanSubTotalResponse.setBeforeTaskMoney(salesPlanSubTotalResponse2.getBeforeTaskMoney());
            salesPlanSubTotalResponse.setTaskMoney(salesPlanSubTotalResponse2.getTaskMoney());
            salesPlanSubTotalResponse.setInitTaskCount(salesPlanSubTotalResponse2.getInitTaskCount());
            salesPlanSubTotalResponse.setInitBeforeTaskMoney(salesPlanSubTotalResponse2.getInitBeforeTaskMoney());
            if(salesPlanSubTotalResponse2.getInitBeforeTaskMoney()!=null){
                BigDecimal initTaskMoney = new BigDecimal(salesPlanSubTotalResponse2.getInitBeforeTaskMoney()).multiply(discount);
                salesPlanSubTotalResponse.setInitTaskMoney(initTaskMoney.longValue());
            }
        //计划发布
        }else{
            BigDecimal returnMoney = new BigDecimal(salesPlanSubTotalResponse.getBeforeReturnMoney()).multiply(discount);
            salesPlanSubTotalResponse.setReturnMoney(returnMoney.longValue());
            //查询计划明细合计得到总调整量
            SubTotalSalesPlanLineRequest subTotalPlanRequest = new SubTotalSalesPlanLineRequest();
            if(Objects.nonNull(queryDimension)){
                BeanUtils.copyProperties(queryDimension, subTotalPlanRequest);
            }
            BeanUtils.copyProperties(subTotalRequest, subTotalPlanRequest);
            subTotalPlanRequest.setPlanId(Long.valueOf(subTotalRequest.getPlanId()));
            SalesPlanSubTotalResponse salesPlanSubTotalAdjustResponse = salesPlanLineRepository.subTotalSalesPlanLine(subTotalPlanRequest);
            salesPlanSubTotalResponse.setAdjustCount(salesPlanSubTotalAdjustResponse.getAdjustCount());
            salesPlanSubTotalResponse.setAdjustOutboundMoney(salesPlanSubTotalAdjustResponse.getAdjustOutboundMoney());
            salesPlanSubTotalResponse.setBeforeAdjustMoney(salesPlanSubTotalAdjustResponse.getBeforeAdjustMoney());
            if(salesPlanSubTotalResponse.getBeforeAdjustMoney()!=null){
                BigDecimal adjustMoney = new BigDecimal(salesPlanSubTotalResponse.getBeforeAdjustMoney()).multiply(discount);
                salesPlanSubTotalResponse.setAdjustMoney(adjustMoney.longValue());
            }
            //初始任务量
            if(salesPlan.getStatus()>= SalesPlanStatusEnum.PUBLISHED.getCode()){
                salesPlanSubTotalResponse.setInitTaskCount(salesPlanSubTotalAdjustResponse.getInitTaskCount());
                salesPlanSubTotalResponse.setInitBeforeTaskMoney(salesPlanSubTotalAdjustResponse.getInitBeforeTaskMoney());
                if(salesPlanSubTotalResponse.getInitBeforeTaskMoney()!=null){
                    BigDecimal initTaskMoney = new BigDecimal(salesPlanSubTotalResponse.getInitBeforeTaskMoney()).multiply(discount);
                    salesPlanSubTotalResponse.setInitTaskMoney(initTaskMoney.longValue());
                }
            }else{
                salesPlanSubTotalResponse.setInitTaskCount(0);
                salesPlanSubTotalResponse.setInitBeforeTaskMoney(0L);
                salesPlanSubTotalResponse.setInitTaskMoney(0L);
            }

            //公司任务量，重新获取任务量
//            if(SalesStatBizTypeEnum.BUSINESS_UNIT.getOrganizationType().equals(pageQueryPlanScItemExtendRequest.getQueryBizType())){
//                Integer companyTaskCount = salesPlanSubTotalResponse.getCompanyTaskCount();
//                BigDecimal costInsuranceFreight = new BigDecimal(salesPlanSubTotalResponse.getBeforeTaskMoney()).divide(new BigDecimal(salesPlanSubTotalResponse.getTaskCount()),2,BigDecimal.ROUND_HALF_UP);
//                Long beforeTaskMoney = costInsuranceFreight.longValue()*companyTaskCount.longValue();
//                salesPlanSubTotalResponse.setTaskCount(companyTaskCount);
//                salesPlanSubTotalResponse.setBeforeTaskMoney(beforeTaskMoney);
//                BigDecimal taskMoney = new BigDecimal(beforeTaskMoney).multiply(discount);
//                salesPlanSubTotalResponse.setTaskMoney(taskMoney.longValue());
//            }
            //部门任务量，重新获取回复量
            if(SalesStatBizTypeEnum.SALES_DEPARTMENT.getOrganizationType().equals(pageQueryPlanScItemExtendRequest.getQueryBizType())){
                SubTotalCompanyReturnCountRequest subTotalReturnCountRequest = new SubTotalCompanyReturnCountRequest();
                BeanUtils.copyProperties(subTotalRequest, subTotalReturnCountRequest);
                subTotalReturnCountRequest.setPlanId(Long.valueOf(subTotalRequest.getPlanId()));
                SubTotalCompanyReturnCountResponse subTotalCompanyReturnCountResponse = planScItemExtendService.subTotalCompanyReturnCount(subTotalReturnCountRequest);
                salesPlanSubTotalResponse.setReturnCount(getMoney(subTotalCompanyReturnCountResponse.getReturnCount()));
                salesPlanSubTotalResponse.setBeforeReturnMoney(getMoney(subTotalCompanyReturnCountResponse.getBeforeReturnMoney()));
                salesPlanSubTotalResponse.setReturnMoney(new BigDecimal(salesPlanSubTotalResponse.getBeforeReturnMoney()).multiply(discount).longValue());
                salesPlanSubTotalResponse.setReturnOutboundMoney(getMoney(subTotalCompanyReturnCountResponse.getReturnOutboundMoney()));
            }
        }

        //合计crm合同量
        SubTotalCompanyCrmContractCountRequest subTotalCompanyCrmContractCountRequest = new SubTotalCompanyCrmContractCountRequest();
        subTotalCompanyCrmContractCountRequest.setContractYear(DateUtils.toDateStr(Long.valueOf(salesPlan.getPlanTime()),"yyyy"));
        subTotalCompanyCrmContractCountRequest.setOrgBusinessUnitCode(salesPlan.getOrgBusinessUnitCode());
        subTotalCompanyCrmContractCountRequest.setScItemIdList(subTotalRequest.getScItemIdList());
        subTotalCompanyCrmContractCountRequest.setScItemCategoryIdList(subTotalRequest.getScItemLeafCategoryIdList());
        Result<Contract> contractResult = contractService.subTotalCompanyCrmContractCount(subTotalCompanyCrmContractCountRequest);
        Contract contract = contractResult.getResult();
        setSubTotalContractCount(DateUtils.toDateStr(Long.valueOf(salesPlan.getPlanTime()),"MM"),contract,salesPlanSubTotalResponse);
        return Result.success(salesPlanSubTotalResponse);
    }


    private SubTotalSalesPlanLineRequest getQueryDimension(PageQueryPlanScItemExtendRepoRequest subTotalRequest){
        SubTotalSalesPlanLineRequest subTotalSalesPlanLineRequest = new SubTotalSalesPlanLineRequest();
        SalesStatBizTypeEnum byOrganizationType = SalesStatBizTypeEnum.match(subTotalRequest.getBizType());
        if(byOrganizationType == null){
            return null;
        }
        switch (byOrganizationType) {
            case SALESMAN:
                subTotalSalesPlanLineRequest.setManageEmployeeIdList(Lists.newArrayList(subTotalRequest.getSubTotalBizId()));
                break;
            case SALES_DEPARTMENT:
                subTotalSalesPlanLineRequest.setOrgSalesDepartmentCode(subTotalRequest.getSubTotalBizId());
                break;
            case SALES_CHANNEL:
                subTotalSalesPlanLineRequest.setOrgSalesChannelCode(subTotalRequest.getSubTotalBizId());
                break;
            case SALES_ORGANIZATION:
                subTotalSalesPlanLineRequest.setOrgSalesOrganizationCode(subTotalRequest.getSubTotalBizId());
                break;
            case BUSINESS_UNIT:
                subTotalSalesPlanLineRequest.setOrgBusinessUnitCode(subTotalRequest.getSubTotalBizId());
                break;
            default:
        }
        return subTotalSalesPlanLineRequest;
    }

    public void setSubTotalContractCount(String month, Contract contract,SalesPlanSubTotalResponse salesPlanSubTotalResponse){
        Long crmMonthContractCount = null;
        Long crmBeforeMonthContractMoney = null;
        Long crmMonthContractMoney = null;
        switch (month){
            case "01" :
                crmMonthContractCount = getCount(contract.getJanQuantity());
                crmBeforeMonthContractMoney = getMoney(contract.getJanTaxIncludedBeforeTax());
                crmMonthContractMoney = getMoney(contract.getJanAmount());
                break;
            case "02" :
                crmMonthContractCount = getCount(contract.getFebQuantity());
                crmBeforeMonthContractMoney = getMoney(contract.getFebTaxIncludedBeforeTax());
                crmMonthContractMoney = getMoney(contract.getFebAmount());
                break;
            case "03" :
                crmMonthContractCount = getCount(contract.getMarQuantity());
                crmBeforeMonthContractMoney = getMoney(contract.getMarTaxIncludedBeforeTax());
                crmMonthContractMoney = getMoney(contract.getMarAmount());
                break;
            case "04" :
                crmMonthContractCount = getCount(contract.getAprQuantity());
                crmBeforeMonthContractMoney = getMoney(contract.getAprTaxIncludedBeforeTax());
                crmMonthContractMoney = getMoney(contract.getAprAmount());
                break;
            case "05" :
                crmMonthContractCount = getCount(contract.getMayQuantity());
                crmBeforeMonthContractMoney = getMoney(contract.getMayTaxIncludedBeforeTax());
                crmMonthContractMoney = getMoney(contract.getMayAmount());
                break;
            case "06" :
                crmMonthContractCount = getCount(contract.getJuneQuantity());
                crmBeforeMonthContractMoney = getMoney(contract.getJuneTaxIncludedBeforeTax());
                crmMonthContractMoney = getMoney(contract.getJuneAmount());
                break;
            case "07" :
                crmMonthContractCount = getCount(contract.getJulyQuantity());
                crmBeforeMonthContractMoney = getMoney(contract.getJulyTaxIncludedBeforeTax());
                crmMonthContractMoney = getMoney(contract.getJulyAmount());
                break;
            case "08" :
                crmMonthContractCount = getCount(contract.getAugQuantity());
                crmBeforeMonthContractMoney = getMoney(contract.getAugTaxIncludedBeforeTax());
                crmMonthContractMoney = getMoney(contract.getAugAmount());
                break;
            case "09" :
                crmMonthContractCount = getCount(contract.getSeptQuantity());
                crmBeforeMonthContractMoney = getMoney(contract.getSeptTaxIncludedBeforeTax());
                crmMonthContractMoney = getMoney(contract.getSeptAmount());
                break;
            case "10" :
                crmMonthContractCount = getCount(contract.getOctQuantity());
                crmBeforeMonthContractMoney = getMoney(contract.getOctTaxIncludedBeforeTax());
                crmMonthContractMoney = getMoney(contract.getOctAmount());
                break;
            case "11" :
                crmMonthContractCount = getCount(contract.getNovQuantity());
                crmBeforeMonthContractMoney = getMoney(contract.getNovTaxIncludedBeforeTax());
                crmMonthContractMoney = getMoney(contract.getNovAmount());
                break;
            case "12" :
                crmMonthContractCount = getCount(contract.getDecQuantity());
                crmBeforeMonthContractMoney = getMoney(contract.getDecTaxIncludedBeforeTax());
                crmMonthContractMoney = getMoney(contract.getDecAmount());
                break;
            default:
                crmMonthContractCount = 0L;
                crmBeforeMonthContractMoney = 0L;
                crmMonthContractMoney = 0L;
        }

        salesPlanSubTotalResponse.setCrmMonthContractCount(crmMonthContractCount);
        salesPlanSubTotalResponse.setCrmBeforeMonthContractMoney(crmBeforeMonthContractMoney);
        salesPlanSubTotalResponse.setCrmMonthContractMoney(crmMonthContractMoney);
    }

    private Long getCount(Integer i){
        if(i == null){
            return 0L;
        }
        return i.longValue();
    }

    private Long getMoney(Long l){
        if(l == null){
            return 0L;
        }
        return l;
    }

    private PageQueryPlanScItemExtendRepoRequest getQueryPlanScItemExtendRequest(PageQueryPlanScItemExtendRequest pageQueryPlanScItemExtendRequest,SalesPlanSDO salesPlan) {
        DimensionDTO dimensionDTO = salesPlanCommonService.checkBizType(salesPlan, pageQueryPlanScItemExtendRequest);
        if (pageQueryPlanScItemExtendRequest.getBizType() > pageQueryPlanScItemExtendRequest.getQueryBizType()) {
            throw new FacadeException("OTS-02-004-01-15-008");
        }
        PageQueryPlanScItemExtendRepoRequest extendRepoRequest = new PageQueryPlanScItemExtendRepoRequest();
        BeanUtils.copyProperties(pageQueryPlanScItemExtendRequest, extendRepoRequest);
        extendRepoRequest.setPoolType(StatPoolTypeEnum.SC_ITEM.getPoolType());
        //如果bizType = queryBizType
        if (pageQueryPlanScItemExtendRequest.getBizType().equals(pageQueryPlanScItemExtendRequest.getQueryBizType())) {
            extendRepoRequest.setBizType(dimensionDTO.getBizType());
            extendRepoRequest.setBizId(Lists.newArrayList(dimensionDTO.getBizId()));
        } else {
            SalesStatBizTypeEnum statBizTypeEnum = SalesStatBizTypeEnum.getByOrganizationType(pageQueryPlanScItemExtendRequest.getQueryBizType());
            if (statBizTypeEnum == null) {
                throw new FacadeException("OTS-02-002-02-15-007");
            }
            OrganizationListQueryRequest organizationListQueryRequest = new OrganizationListQueryRequest();
            organizationListQueryRequest.setType(pageQueryPlanScItemExtendRequest.getQueryBizType()!=null?
                    pageQueryPlanScItemExtendRequest.getQueryBizType(): OrganizationTypeEnum.SALES_DEPARTMENT.getCode());
            organizationListQueryRequest.setId(pageQueryPlanScItemExtendRequest.getBizId());
            List<com.epoch.app.crplatformenhance.sdo.OrganizationSDO> getDownOrganizationList = platformEnhanceRepository.getDownOrganizationList(organizationListQueryRequest);
            if (CollectionUtils.isEmpty(getDownOrganizationList)) {
                throw new FacadeException("OTS-02-004-01-15-030");
            }
            List<String> orgIdList = getDownOrganizationList.stream().map(com.epoch.app.crplatformenhance.sdo.OrganizationSDO::getId).collect(Collectors.toList());
            extendRepoRequest.setBizType(statBizTypeEnum.getBizType());
            extendRepoRequest.setBizId(orgIdList);
        }
        extendRepoRequest.setSubTotalBizId(dimensionDTO.getBizId());
        //增加货品编码查询
        List<String> scItemIdList = new ArrayList<>();
        if (StringUtils.isNotBlank(pageQueryPlanScItemExtendRequest.getScItemId())) {
            scItemIdList.add(pageQueryPlanScItemExtendRequest.getScItemId());
            extendRepoRequest.setScItemId(null);
        }
        if (CollectionUtils.isNotEmpty(pageQueryPlanScItemExtendRequest.getScItemIdList())) {
            scItemIdList.addAll(pageQueryPlanScItemExtendRequest.getScItemIdList());
        }
        if (StringUtils.isNotBlank(pageQueryPlanScItemExtendRequest.getScItemCode())) {
            Map<String, ScItemSDO> scItemMap = salesPlanOutCommonService.getScItemMapByOutId(Sets.newHashSet(pageQueryPlanScItemExtendRequest.getScItemCode()));
            if(scItemMap != null){
                scItemIdList.addAll(scItemMap.values().stream().map(x->x.getScItemId()).collect(Collectors.toList()));
            }else{
                scItemIdList.add("-1");
            }
        }
        if(CollectionUtils.isNotEmpty(scItemIdList)){
            extendRepoRequest.setScItemIdList(scItemIdList);
        }

        //增加货品类目多选查询
        List<String> scItemLeafCategoryIdList = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(pageQueryPlanScItemExtendRequest.getScItemLeafCategoryIdList())) {
            scItemLeafCategoryIdList.addAll(pageQueryPlanScItemExtendRequest.getScItemLeafCategoryIdList());
        }
        if (StringUtils.isNotEmpty(pageQueryPlanScItemExtendRequest.getScItemLeafCategoryId())) {
            scItemLeafCategoryIdList.add(pageQueryPlanScItemExtendRequest.getScItemLeafCategoryId());
        }
        if(CollectionUtils.isNotEmpty(scItemLeafCategoryIdList)){
            extendRepoRequest.setScItemLeafCategoryIdList(scItemLeafCategoryIdList);
        }

        return extendRepoRequest;
    }
}
